package railRoad.db;

import java.sql.Connection;
import java.sql.SQLException;

import railRoad.exception.DBException;
import railRoad.exception.OpenFileException;
import railRoad.io.AbstractReaderWriter;

/**
 * Abstract class for routine with database
 * 
 * @see H2Reader
 * @see AbstractReaderWriter
 * @author Rukin
 *
 */
public abstract class DBReader extends AbstractReaderWriter{
	
	 private final DBConectionPool conectionPool = DBConectionPool.getInstance();
	
	/**
	 * You must call {@link#close()} after routine to close {@link#DBConectionPool}
	 * @throws OpenFileException throws if property file can't be found
	 * @throws DBException throws if wrong parameters number
	 */
	public void open(String login, String pass) throws OpenFileException
	{	
		conectionPool.open(login, pass);
	}
	
	/**
	 * Closing conection pool {@link#DBConectionPool}
	 */
	public void close() throws SQLException {
		conectionPool.close();
	}
	
	/**
	 * Closing connection to database
	 * @param conn {@link#Connection}
	 */
	protected void close(Connection conn)
	{
		conectionPool.close(conn);
	}
	
	/**
	 * Return {@link#Connection} from connection pool {@link#DBConectionPool}
	 * @return database connection {@link#Connection}
	 * @throws SQLException
	 */
	protected Connection getConnection() throws SQLException {
		return conectionPool.getConnection();
	}
	
	
	/**
	 * Select T from database by it id
	 * 
	 * @param object class that tells witch implementation of {@link#IDAO} use for select
	 * @param parentId
	 *            id parameter to search
	 * @return result of select
	 * @throws DBException
	 */
	public abstract<T> T select(T object, int id) throws DBException;
	
	/**
	 * Select T from database by it unique field
	 * 
	 * @param object class that tells witch implementation of {@link#IDAO} use for select
	 * @param field value of unique parameter
	 * @return result of select
	 * @throws DBException
	 */
	public abstract<T> T select(T object, String field) throws DBException;
	
	/**
	 * Insert new object into database
	 * 
	 * @param object class that tells witch implementation of {@link#IDAO} use for insert
	 * @param parentId foreign key if need
	 * @throws DBException
	 */
	public abstract<T> void insert(T object, int parentId) throws DBException;;
	
	/**
	 * update object in database
	 * @param object class that tells witch implementation of {@link#IDAO} use for update
	 * @throws DBException
	 */
	public abstract<T> void update(T object) throws DBException;
	
	/**
	 * delete object from database
	 * @param object class that tells witch implementation of {@link#IDAO} use for delete
	 * @throws DBException
	 */
	public abstract<T> void delete(T object) throws DBException;
	
}
